package com.yupi.oj.controller;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.google.gson.Gson;
import com.yupi.oj.annotation.AuthCheck;
import com.yupi.oj.common.BaseResponse;
import com.yupi.oj.common.DeleteRequest;
import com.yupi.oj.common.ErrorCode;
import com.yupi.oj.common.ResultUtils;
import com.yupi.oj.constant.UserConstant;
import com.yupi.oj.exception.BusinessException;
import com.yupi.oj.exception.ThrowUtils;
import com.yupi.oj.model.dto.questioninfo.*;
import com.yupi.oj.model.entity.QuestionInfo;
import com.yupi.oj.model.entity.User;
import com.yupi.oj.model.vo.QuestionInfoVO;
import com.yupi.oj.service.QuestionInfoService;
import com.yupi.oj.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.List;

/**
 * 题目信息接口
 *
 * @author <a href="https://github.com/liyupi">程序员鱼皮</a>
 * @from <a href="https://yupi.icu">编程导航知识星球</a>
 */
@RestController
@RequestMapping("/questionInfo")
@Slf4j
public class QuestionController {

    @Resource
    private QuestionInfoService questionInfoService;

    @Resource
    private UserService userService;

    private final static Gson GSON = new Gson();

    // region 增删改查

    /**
     * 创建
     *
     * @param questionInfoAddRequest
     * @param request
     * @return
     */
    @PostMapping("/add")
    public BaseResponse<Long> addQuestionInfo(@RequestBody QuestionInfoAddRequest questionInfoAddRequest, HttpServletRequest request) {
        if (questionInfoAddRequest == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        QuestionInfo questionInfo = new QuestionInfo();
        BeanUtils.copyProperties(questionInfoAddRequest, questionInfo);
        List<String> tags = questionInfoAddRequest.getTags();
        JudgeConfig judgeConfig = questionInfoAddRequest.getJudgeConfig();
        List<JudgeCase> judgeCases = questionInfoAddRequest.getJudgeCase();
        if (tags != null) {
            questionInfo.setTags(GSON.toJson(tags));
        }
        if (judgeConfig != null) {
            questionInfo.setJudgeConfig(GSON.toJson(judgeConfig));
        }
        if (judgeCases != null) {
            questionInfo.setJudgeCase(GSON.toJson(judgeCases));
        }

        questionInfoService.validQuestionInfo(questionInfo, true);
        User loginUser = userService.getLoginUser(request);
        questionInfo.setUserId(loginUser.getId());
        questionInfo.setFavourNum(0);
        questionInfo.setThumbNum(0);
        boolean result = questionInfoService.save(questionInfo);
        ThrowUtils.throwIf(!result, ErrorCode.OPERATION_ERROR);
        long newQuestionInfoId = questionInfo.getId();
        return ResultUtils.success(newQuestionInfoId);
    }

    /**
     * 删除
     *
     * @param deleteRequest
     * @param request
     * @return
     */
    @DeleteMapping("/delete")
    public BaseResponse<Boolean> deleteQuestionInfo(@RequestBody DeleteRequest deleteRequest, HttpServletRequest request) {
        if (deleteRequest == null || deleteRequest.getId() <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        User user = userService.getLoginUser(request);
        long id = deleteRequest.getId();
        // 判断是否存在
        QuestionInfo oldQuestionInfo = questionInfoService.getById(id);
        ThrowUtils.throwIf(oldQuestionInfo == null, ErrorCode.NOT_FOUND_ERROR);
        // 仅本人或管理员可删除
        if (!oldQuestionInfo.getUserId().equals(user.getId()) && !userService.isAdmin(request)) {
            throw new BusinessException(ErrorCode.NO_AUTH_ERROR);
        }
        boolean b = questionInfoService.removeById(id);
        return ResultUtils.success(b);
    }

    /**
     * 更新（仅管理员）
     *
     * @param questionInfoUpdateRequest
     * @return
     */
    @PutMapping("/update")
    @AuthCheck(mustRole = UserConstant.ADMIN_ROLE)
    public BaseResponse<Boolean> updateQuestionInfo(@RequestBody QuestionInfoUpdateRequest questionInfoUpdateRequest) {
        if (questionInfoUpdateRequest == null || questionInfoUpdateRequest.getId() <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        QuestionInfo questionInfo = new QuestionInfo();
        BeanUtils.copyProperties(questionInfoUpdateRequest, questionInfo);
        List<String> tags = questionInfoUpdateRequest.getTags();
        if (tags != null) {
            questionInfo.setTags(GSON.toJson(tags));
        }
        // 参数校验
        questionInfoService.validQuestionInfo(questionInfo, false);
        long id = questionInfoUpdateRequest.getId();
        // 判断是否存在
        QuestionInfo oldQuestionInfo = questionInfoService.getById(id);
        ThrowUtils.throwIf(oldQuestionInfo == null, ErrorCode.NOT_FOUND_ERROR);
        boolean result = questionInfoService.updateById(questionInfo);
        return ResultUtils.success(result);
    }

    /**
     * 根据 id 获取
     *
     * @param id
     * @return
     */
    @GetMapping("/get/vo")
    public BaseResponse<QuestionInfoVO> getQuestionInfoVOById(long id, HttpServletRequest request) {
        if (id <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        QuestionInfo questionInfo = questionInfoService.getById(id);
        if (questionInfo == null) {
            throw new BusinessException(ErrorCode.NOT_FOUND_ERROR);
        }
        return ResultUtils.success(questionInfoService.getQuestionInfoVO(questionInfo, request));
    }

    /**
     * 分页获取列表（封装类）
     *
     * @param questionInfoQueryRequest
     * @param request
     * @return
     */
    @GetMapping("/list/page/vo")
    public BaseResponse<Page<QuestionInfoVO>> listQuestionInfoVOByPage(QuestionInfoQueryRequest questionInfoQueryRequest,
                                                                       HttpServletRequest request) {
        long current = questionInfoQueryRequest.getCurrent();
        long size = questionInfoQueryRequest.getPageSize();
        // 限制爬虫
        ThrowUtils.throwIf(size > 20, ErrorCode.PARAMS_ERROR);
        Page<QuestionInfo> questionInfoPage = questionInfoService.page(new Page<>(current, size),
                questionInfoService.getQueryWrapper(questionInfoQueryRequest));
        return ResultUtils.success(questionInfoService.getQuestionInfoVOPage(questionInfoPage, request));
    }

    /**
     * 分页获取当前用户创建的资源列表
     *
     * @param questionInfoQueryRequest
     * @param request
     * @return
     */
    @GetMapping("/my/list/page/vo")
    public BaseResponse<Page<QuestionInfoVO>> listMyQuestionInfoVOByPage(QuestionInfoQueryRequest questionInfoQueryRequest,
                                                                         HttpServletRequest request) {
        if (questionInfoQueryRequest == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        User loginUser = userService.getLoginUser(request);
        questionInfoQueryRequest.setUserId(loginUser.getId());
        long current = questionInfoQueryRequest.getCurrent();
        long size = questionInfoQueryRequest.getPageSize();
        // 限制爬虫
        ThrowUtils.throwIf(size > 20, ErrorCode.PARAMS_ERROR);
        Page<QuestionInfo> questionInfoPage = questionInfoService.page(new Page<>(current, size),
                questionInfoService.getQueryWrapper(questionInfoQueryRequest));
        return ResultUtils.success(questionInfoService.getQuestionInfoVOPage(questionInfoPage, request));
    }

    // endregion


    /**
     * 编辑（用户）
     *
     * @param questionInfoEditRequest
     * @param request
     * @return
     */
    @PutMapping("/edit")
    public BaseResponse<Boolean> editQuestionInfo(@RequestBody QuestionInfoEditRequest questionInfoEditRequest, HttpServletRequest request) {
        if (questionInfoEditRequest == null || questionInfoEditRequest.getId() <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        QuestionInfo questionInfo = new QuestionInfo();
        BeanUtils.copyProperties(questionInfoEditRequest, questionInfo);
        List<String> tags = questionInfoEditRequest.getTags();
        if (tags != null) {
            questionInfo.setTags(GSON.toJson(tags));
        }
        // 参数校验
        questionInfoService.validQuestionInfo(questionInfo, false);
        User loginUser = userService.getLoginUser(request);
        long id = questionInfoEditRequest.getId();
        // 判断是否存在
        QuestionInfo oldQuestionInfo = questionInfoService.getById(id);
        ThrowUtils.throwIf(oldQuestionInfo == null, ErrorCode.NOT_FOUND_ERROR);
        // 仅本人或管理员可编辑
        if (!oldQuestionInfo.getUserId().equals(loginUser.getId()) && !userService.isAdmin(loginUser)) {
            throw new BusinessException(ErrorCode.NO_AUTH_ERROR);
        }
        boolean result = questionInfoService.updateById(questionInfo);
        return ResultUtils.success(result);
    }

}
